package com.lb.shopguide.ui.fragment.guide.order;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterGoodsInOrderCommon;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.order.CommitChangePriceBean;
import com.lb.shopguide.entity.order.GoodsInOrderBean;
import com.lb.shopguide.entity.order.OrderDetailBean;
import com.lb.shopguide.event.guide.ChangePriceEvent;
import com.lb.shopguide.event.guide.CloseOrderEvent;
import com.lb.shopguide.event.guide.OrderChangeEvent;
import com.lb.shopguide.event.guide.SendGoodsEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.dialog.DialogLbCommon;
import com.lb.shopguide.ui.dialog.DialogMakeSure;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizGoodsUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/6/3.
 */

public class FragmentOrderDetail extends BaseCommonFragment implements View.OnClickListener {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.layout_order_bottom)
    RelativeLayout layoutBottom;
    @BindView(R.id.tv_check_delivery)
    TextView tvCheckDelivery;
    @BindView(R.id.tv_deliver_goods)
    TextView tvDeliveryGoods;
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.tv_close_order)
    TextView tvCloseOrder;
    @BindView(R.id.tv_pay_count_down)
    TextView tvCountDown;
    //    @BindView(R.id.tv_deliver_goods)
//    TextView tvSendGoods;
    @BindView(R.id.tv_change_price)
    TextView tvChangePrice;
    @BindView(R.id.layout_discount)
    RelativeLayout layoutDiscount;
    @BindView(R.id.tv_avatar)
    TextView tvUserName;
    @BindView(R.id.tv_order_code)
    TextView tvOrderCode;
    @BindView(R.id.tv_order_type)
    TextView tvOrderType;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R.id.tv_deliver_type)
    TextView tvDeliverType;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_guider_name)
    TextView tvGuiderName;
    @BindView(R.id.tv_beizhu_info)
    TextView tvBeizhuInfo;
    @BindView(R.id.tv_price_total)
    TextView tvPriceTotal;
    @BindView(R.id.tv_price_discount)
    TextView tvPriceDiscount;
    @BindView(R.id.tv_deliver_fee)
    TextView tvDeliverFee;
    @BindView(R.id.tv_should_pay)
    TextView tvShouldPay;
    @BindView(R.id.tv_order_goods_sum)
    TextView tvGoodsSum;

    private String orderNum;
    private MyCountDown countDown;
    private int fromMode;

    private List<GoodsInOrderBean> mGoodsInOrderList;
    private AdapterGoodsInOrderCommon mAdapterGoodsInOrderCommon;

    private OrderDetailBean mOrderDetailBean;


    public static FragmentOrderDetail newInstance(String orderNum, int comeMode) {
        FragmentOrderDetail fragment = new FragmentOrderDetail();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.ORDER_NUM, orderNum);
        bundle.putInt(AppConstant.FROM_MODE, comeMode);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_order_detail;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.ORDER_NUM)) {
            orderNum = bundle.getString(AppConstant.ORDER_NUM);
            sendRequestGetOrderDetail(orderNum);
        }
        if (bundle.containsKey(AppConstant.FROM_MODE)) {
            fromMode = bundle.getInt(AppConstant.FROM_MODE);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        ntb.setTitleText("订单详情");
        ntb.setLeftImageSrc(R.drawable.iv_back_white);
        ntb.setTitleColor(getResources().getColor(R.color.white));
        ntb.setBackground(getResources().getColor(R.color.sg_common_red));
        ntb.setOnLeftImageListener(this);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterGoodsInOrderCommon = new AdapterGoodsInOrderCommon(R.layout.layout_goods_base_order, mGoodsInOrderList);
        mRecyclerView.setAdapter(mAdapterGoodsInOrderCommon);

        initListener();

    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentOrderDetail.class.getName();
    }


    private void bindData() {

    }

    private void initListener() {
        tvCheckDelivery.setOnClickListener(this);
        tvCloseOrder.setOnClickListener(this);
//        tvSendGoods.setOnClickListener(this);
        tvChangePrice.setOnClickListener(this);
        tvDeliveryGoods.setOnClickListener(this);
        Observer<List<IMMessage>> incomingMessageObserver =
                new Observer<List<IMMessage>>() {
                    @Override
                    public void onEvent(List<IMMessage> messages) {
                        // 处理新收到的消息，为了上传处理方便，SDK 保证参数 messages 全部来自同一个聊天对象。
                    }
                };
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, true);
    }

    private void bindOrderDetail() {
        mGoodsInOrderList = mOrderDetailBean.getOrderDetailList();
        bindData();
        if (!mOrderDetailBean.isTourist()) {
            tvUserName.setText(mOrderDetailBean.getNickName() + "(" + mOrderDetailBean.getTrueName() + ")");
        } else {
            tvUserName.setText("游客");
        }
        tvOrderCode.setText(mOrderDetailBean.getOrderNum());
        tvBeizhuInfo.setText(mOrderDetailBean.getLeaveMessage());
        tvDeliverFee.setText("￥" + mOrderDetailBean.getExpressFee());

        if (mOrderDetailBean.getDistributeMode() == AppConstant.DISTRIBUTE_MODE_PICK) {
            tvDeliverType.setText("自提");
        } else if (mOrderDetailBean.getDistributeMode() == AppConstant.DISTRIBUTE_MODE_EXPRESS) {
            tvDeliverType.setText("快递");
        }

        tvGuiderName.setText(mOrderDetailBean.getStaffName());

        switch (mOrderDetailBean.getOrderType()) {
            case AppConstant.ORDER_IN_APP:
                tvOrderType.setText("APP下单");
                break;
            case AppConstant.ORDER_IN_SHOP:
            case AppConstant.ORDER_IN_CHECKOUT:
                tvOrderType.setText("门店下单");
                break;
        }
        tvShopName.setText(mOrderDetailBean.getStoreName());
        tvOrderTime.setText(mOrderDetailBean.getCreateTime());
        tvPayType.setText("" + mOrderDetailBean.getPayMode());
        switch (mOrderDetailBean.getPayMode()) {
            case AppConstant.PAY_TYPE_ALIPAY:
                tvPayType.setText("支付宝");
                break;
            case AppConstant.PAY_TYPE_WECHAT_PAY:
                tvPayType.setText("微信");
                break;
            case AppConstant.PAY_TYPE_CASH_PAY:
                tvPayType.setText("现金");
                break;
            case AppConstant.PAY_TYPE_BALANCE_PAY:
                tvPayType.setText("余额支付");
                break;
            default:
                tvPayType.setText("/");
                break;
        }

        tvShouldPay.setText("￥" + mOrderDetailBean.getOrderActualMoney());
        tvPriceTotal.setText("￥" + mOrderDetailBean.getProductTotalMoney());
        tvPriceDiscount.setText("-￥" + mOrderDetailBean.getProductDiscountMoney());
        tvGoodsSum.setText(String.format(mContext.getResources().
                getString(R.string.format_goods_sum), BizGoodsUtil.
                getTotalSum(mGoodsInOrderList)));
        mAdapterGoodsInOrderCommon.setNewData(mGoodsInOrderList);
        ImageLoaderUtils.displayCircle(mContext, ivAvatar, mOrderDetailBean.getHeadPicUrl());

        tvChangePrice.setVisibility(View.GONE);
        tvDeliveryGoods.setVisibility(View.GONE);
        switch (mOrderDetailBean.getOrderType()) {
            case AppConstant.ORDER_TYPE_SS_EXPRESS://自商城快递
                switch (mOrderDetailBean.getOrderStatus()) {
                    case AppConstant.ORDER_STATUS_NO_PAY:
                        tvOrderStatus.setText("待支付");
                        tvCloseOrder.setVisibility(View.VISIBLE);
                        tvChangePrice.setVisibility(View.VISIBLE);
                        countDown(mOrderDetailBean.getRemainingPaymentTime());
                        break;
                    case AppConstant.ORDER_STATUS_NO_DELIVER:
                        tvOrderStatus.setText("待发货");
                        tvDeliveryGoods.setVisibility(View.VISIBLE);
                        break;
                    case AppConstant.ORDER_STATUS_NO_RECEIVE:
                        tvOrderStatus.setText("已发货");
                        tvCheckDelivery.setVisibility(View.VISIBLE);
                        break;
                    case AppConstant.ORDER_STATUS_FINISHED:
                        tvOrderStatus.setText("已完成");
                        break;
                    case AppConstant.ORDER_STATUS_CLOSED:
                        tvOrderStatus.setText("已关闭");
                        break;
                }
                break;
            case AppConstant.ORDER_TYPE_SS_PICK://自商城自提
                switch (mOrderDetailBean.getOrderStatus()) {
                    case AppConstant.ORDER_STATUS_NO_PAY:
                        tvOrderStatus.setText("待支付");
                        tvCloseOrder.setVisibility(View.VISIBLE);
                        tvChangePrice.setVisibility(View.VISIBLE);
                        countDown(mOrderDetailBean.getRemainingPaymentTime());
                        break;
                    case AppConstant.ORDER_STATUS_NO_PICKUP:
                        tvOrderStatus.setText("待自提");
                        break;
                    case AppConstant.ORDER_STATUS_FINISHED:
                        tvOrderStatus.setText("已完成");
                        break;
                    case AppConstant.ORDER_STATUS_CLOSED:
                        tvOrderStatus.setText("已关闭");
                        break;
                }
                break;
            case AppConstant.ORDER_TYPE_SS_CHECKOUT://收银台
                switch (mOrderDetailBean.getOrderStatus()) {
                    case AppConstant.ORDER_STATUS_NO_PAY:
                        tvOrderStatus.setText("待支付");
                        tvCloseOrder.setVisibility(View.VISIBLE);
                        tvChangePrice.setVisibility(View.VISIBLE);
                        countDown(mOrderDetailBean.getRemainingPaymentTime());
                        break;
                    case AppConstant.ORDER_STATUS_FINISHED:
                        tvOrderStatus.setText("已完成");
                        break;
                    case AppConstant.ORDER_STATUS_CLOSED:
                        tvOrderStatus.setText("已关闭");
                        break;
                }
                break;
        }
    }

    private void sendRequestGetOrderDetail(String orderNum) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mOrderDetailBean = (OrderDetailBean) JsonUtil.getObject(response.getReturnContent(), OrderDetailBean.class);
                    bindOrderDetail();
                }
            }
        };
        ApiMethodGuide.getOrderDetail(new SimpleLbObserver(listener, otherListener), orderNum, this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestCloseOrder(String orderNum) {
        HashMap hashMap = new HashMap();
        hashMap.put("orderNum", orderNum);
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    EventBus.getDefault().post(new CloseOrderEvent());
                    ToastUtils.showShort("关闭订单成功");
                    pop();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        ApiMethodGuide.closeOrder(new SimpleLbObserver(listener, null), body, this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestCommitChangePriceInfo(String info) {
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), info);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    EventBus.getDefault().post(new OrderChangeEvent());
                    sendRequestGetOrderDetail(orderNum);
                    ToastUtils.showShort("改价成功");
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        SimpleObserverOtherListener errorLister = new SimpleObserverOtherListener() {
            @Override
            public void onSessionOutOfDate() {

            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort("改价失败");
            }
        };
        ApiMethodGuide.changePrice(new SimpleLbObserver(listener, errorLister), body, this, FragmentEvent.DESTROY_VIEW);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshOrders(SendGoodsEvent event) {
        if (mUserConfigManager != null) {
            sendRequestGetOrderDetail(orderNum);
        }
    }


    @Subscribe
    public void orderDetailChange(ChangePriceEvent event) {
        List<GoodsInOrderBean> list = event.getList();
        if (list != null && list.size() != 0) {
            List<CommitChangePriceBean> listCommit = new ArrayList<>();
            for (GoodsInOrderBean bean : list) {
                CommitChangePriceBean goodsBean = new CommitChangePriceBean();
                goodsBean.setDiscountPrice(Float.parseFloat(bean.getDiscountPrice()));
                goodsBean.setOrderDetailCode(bean.getOrderDetailCode());
                listCommit.add(goodsBean);
            }
            sendRequestCommitChangePriceInfo(JsonUtil.getGson().toJson(listCommit));
        }

    }

    @Override
    public boolean onBackPressedSupport() {
        if (fromMode == AppConstant.FROM_PAY_ACTIVITY) {
            getActivity().finish();
        } else if (fromMode == AppConstant.FROM_MAIN_ACTIVITY) {
            pop();
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_left:
                if (fromMode == AppConstant.FROM_PAY_ACTIVITY) {
                    getActivity().finish();
                } else if (fromMode == AppConstant.FROM_MAIN_ACTIVITY) {
                    pop();
                }
                break;
            case R.id.tv_check_delivery:
                if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                    start(FragmentCheckDelivery.newInstance("https://singlepage.storeer.com/v2/express?orderNum=" + mOrderDetailBean.getOrderNum()));
                } else {
                    start(FragmentCheckDelivery.newInstance("http://192.168.1.102:8088/v2/express?orderNum=" + mOrderDetailBean.getOrderNum()));
                }
                break;
            case R.id.tv_deliver_goods:
                start(FragmentSendGoods.newInstance(mOrderDetailBean.getOrderNum()));
                break;
            case R.id.tv_close_order:
                DialogMakeSure dialog = new DialogMakeSure(mContext);
                dialog.getDialog("是否关闭该订单?").show();
                dialog.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
                    @Override
                    public void onSure(DialogInterface dialog, int which) {
                        sendRequestCloseOrder(mOrderDetailBean.getOrderNum());
                    }

                    @Override
                    public void onCancel(DialogInterface dialog, int which) {
                    }
                });
                break;
            case R.id.tv_change_price:
                start(FragmentChangePrice.newInstance(mGoodsInOrderList));
                break;
        }
    }

    private void countDown(long time) {
        tvCountDown.setVisibility(View.VISIBLE);
        if (countDown == null) {
            countDown = new MyCountDown(time, 1000);
        }
        countDown.start();
    }


    class MyCountDown extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountDown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvCountDown.setClickable(false);
            tvCountDown.setText(String.format(mContext.getResources().getString(R.string.format_count_down), TimeUtils.millis2String(millisUntilFinished, new SimpleDateFormat("mm:ss"))));

            SpannableString mSp = new SpannableString(tvCountDown.getText().toString());
            mSp.setSpan(new ForegroundColorSpan(Color.rgb(253, 91, 89)), 1, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置前景色为洋红色
            tvCountDown.setText(mSp);
        }

        @Override
        public void onFinish() {
            tvCountDown.setClickable(true);
            tvCountDown.setText("订单已关闭");
            if (getFragmentManager() != null) {
                final DialogLbCommon dialogLbCommon = DialogLbCommon.getDialogLbCommon(AppConstant.DIALOG_COMMON_INFO, "订单已失效", "确定");
                dialogLbCommon.show(getFragmentManager(), getPageTag());
                dialogLbCommon.setOnOneButtonClickListener(new DialogLbCommon.OnOneButtonClickListener() {
                    @Override
                    public void onOneButtonClick() {
                        dialogLbCommon.dismiss();
                        pop();
                    }
                });
            }
        }

    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
